/** 
  *@CopyRight(c)2009 company Co.Ltd. 
  *@All right reserved.
  *@module name: App.Base.SystemMainFrame.SysMainFrame
  *@description:
  *
  *@author: lugj
  *@version: 1.0
  *@date: 2009/06/05
  *@last date: 2009/06/30
  *@history:
    1.
    2.
  *@bugs:
    1. 
    2. include文件路径问题，执行路径与文件存在路径，for example： <php dirname(__FILE__)>
  *
*/ 

Ext.namespace("App.Base.SystemMainFrame");

App.Base.SystemMainFrame.SysMainFrame = function(){
    //private constant.   

    //private vars, 'the classes shared its'.
    var maincssstylesheetcombox = null;
    var maintoptoolbar = null;
    var mainbottomtoolbar = null;
    //var mainiframepanel = null;
    var maincentertabpanel = null;
    var mainwesttreepanel = null;
    var mainwesttreerootnode = null;
    var mainwesttreecontextmenu = null;
    var mainviewport = null;

    //private constructor function.    
    var __constructor = function(){
    }();
    
	var MODULE_ID = 'SYSMAINFRM';

    function swapCssStyleSheet(cssfilepath)
    {
        Ext.util.CSS.swapStyleSheet('theme', cssfilepath);
        //document.getElementById('theme').setAttribute('href', cssFilePath);
        
        //changing the iframe's skin.
        /*var obj = document.getElementById("oamainIframe").contentWindow.document.getElementById('theme');
        if (obj != null)
        {
            obj.setAttribute('href', cssFilePath);
        }*/
    }

    //configuration core: extending the system modules. 
    function createTabPageByTreeLeafNode(tabPanel, selectedTreeNode)
    {
		if(tabPanel == null || selectedTreeNode == null)
		{
			alert('createTabPageByTreeLeafNode() : the Params of object is null!!!');
			return;
		}

		var tagPageId = selectedTreeNode.id.trim();
		var tagPageTitle = selectedTreeNode.text.trim();

		var actionModuleConfig = selectedTreeNode.attributes['actionModuleConfig'];

		if (App.Base.Common.func.isEmptyString(actionModuleConfig))
		{
			App.Base.Common.func.MESSAGEBOX_SHOW({
				title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
				msg: '系统参数配置错误：系统参数[actionModuleConfig]不存在',
				icon: Ext.MessageBox.ERROR
			});
			return;
		}

		actionModuleConfig = actionModuleConfig.trim();

		//alert(actionModuleConfig);

		var config = actionModuleConfig.split(App.Base.common.param.SPLIT_CHARS_VERTICAL_LINE);
		//alert( config.length);
		
		for (var index = 0; index < config.length; index++)
		{
			config[index] = config[index].trim();

			if (App.Base.Common.func.isEmptyString(config[index]))
			{
				App.Base.Common.func.MESSAGEBOX_SHOW({
					title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
					msg: 'the configuation of params actionModuleConfig[' +  index +'] error!!!',
					icon: Ext.MessageBox.ERROR
				});

				return;
			}
		}

		var tabPage = tabPanel.getItem('tabPage' + tagPageId); 

		if (Ext.isEmpty(tabPage))
        {
			var moduleObject = null;

			try
			{
				moduleObject = eval(config[0]);                            
			}
			catch (err)
			{
				App.Base.Common.func.MESSAGEBOX_SHOW({
					title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
					msg: '系统菜单项配置参数[actionModuleConfig]配置错误：' + err,
					icon: Ext.MessageBox.ERROR
				});
				
				return;
			}

            if (!Ext.isEmpty(moduleObject))
            {
                var newTabpage = tabPanel.add({
                    id: 'tabPage' + tagPageId,
                    title: tagPageTitle,
					autoScroll: true,
                    border: false,
					hideMode: Ext.isIE ? 'offsets' : 'display', 
					iconCls: 'x-tabpanel-systemmanage-tabpage',
                    layout: 'fit',
                    items: [
                            moduleObject
                        ],
                    closable:true,
					listeners: {
						beforedestroy: function(o){

						},
						scope: this
					}
                });

                tabPanel.setActiveTab(newTabpage);
				newTabpage.doLayout();
            }
            else
            {
				App.Base.Common.func.MESSAGEBOX_SHOW({
					title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
					msg: '系统模块 [' + config[0] + '创建错误，请检查后重试' ,
					icon: Ext.MessageBox.ERROR
				});
            }
        }
		else
		{
			tabPanel.setActiveTab(tabPage);
			tabPage.doLayout();	
		}
    }
    
    function closeTabPageByTreeLeafNode(tabPanel, selectedTreeNode)
    {
		if(tabPanel == null || selectedTreeNode == null)
		{
			alert('createTabPageByTreeLeafNode() : the Params of object is null!!!');
			return;
		}

		var tagPageId = 'tabPage' + selectedTreeNode.id.trim();

		var tabPage = tabPanel.getItem(tagPageId); 

        if (!Ext.isEmpty(tabPage))
        {
            tabPanel.remove(tabPage, true);
        }
    }
    
	function treePanelRefresh(params){
		//自动更新系统菜单目录树
		var node = null;

		if (params.OpCmd == App.Base.common.param.OP_CMD_ADD)
		{
			node = mainwesttreepanel.getNodeById(params.curSelMenuNewPId + MODULE_ID);
			if (!App.Base.Common.func.isUndefinedOrNull(node))
			{
				node.reload();
			}
		}
		else if (params.OpCmd == App.Base.common.param.OP_CMD_MODIFY)
		{
			node = mainwesttreepanel.getNodeById(params.curSelMenuId + MODULE_ID);
			if (!App.Base.Common.func.isUndefinedOrNull(node))
			{
				node.remove();
			}

			node = mainwesttreepanel.getNodeById(params.curSelMenuNewPId + MODULE_ID);
			if (!App.Base.Common.func.isUndefinedOrNull(node))
			{
				node.reload();
			}
		}
		else if (params.OpCmd == App.Base.common.param.OP_CMD_DELETE)
		{
			node = mainwesttreepanel.getNodeById(params.curSelMenuId + MODULE_ID);
			if (!App.Base.Common.func.isUndefinedOrNull(node))
			{
				node.remove();
			}
		}	
	};
    
	return {
        init : function(){
			Ext.getDoc().on("contextmenu",function(e){   
				e.stopEvent();
			});           
			
			Ext.getBody().mask("系统正在加载数据，请稍候...", "x-mask-loading");
			            
			Ext.Ajax.on('requestcomplete', App.Base.Common.func.extLibAjaxRequestComplete , this);

            maintoptoolbar = new Ext.Toolbar({
                border: false,
				frame: false,
                items : ['->', '-',
					{
						text: '换肤',
						iconCls: 'x-menu-systemmanage-changeskins',
						menu: new Ext.menu.Menu({
							items: [{
								text: '默认风格',
								checked: true,
								group: 'theme',
								checkHandler: function(){
									swapCssStyleSheet(App.Base.common.param.SYSTEM_CSS_STYLESHEET_URL + 'ext-all.css');						
								},
								scope: this
							}, '-', {
								text: '灰色风格',
								checked: false,
								group: 'theme',
								checkHandler: function(){
									swapCssStyleSheet(App.Base.common.param.SYSTEM_CSS_STYLESHEET_URL + 'xtheme-gray.css');						
								},
								scope: this
							},{
								text: '暗蓝灰色风格',
								checked: false,
								group: 'theme',
								checkHandler: function(){
									swapCssStyleSheet(App.Base.common.param.SYSTEM_CSS_STYLESHEET_URL + 'xtheme-slate.css');						
								},
								scope: this
							}]
						})
					},
					'-',{
						text: '帮助',
						iconCls: 'x-menu-systemmanage-help'
					},
					'-',{
                        text: '退出',
                        handler: function(){
							Ext.MessageBox.show({
								title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
								msg: '确定要退出系统',
								buttons: Ext.MessageBox.YESNO,
								icon: Ext.MessageBox.QUESTION,
								fn: function(btn){
									if (btn == 'yes')
									{
										App.Base.Common.func.request({
											method: 'POST',
											url: App.Base.common.param.SYSTEM_USER_LOGIN_URL,
											success: function(response){
												mainviewport.destroy();
												window.location = App.Base.common.param.SYSTEM_USER_LOGIN_URL;
											},
											failure: function(){
												App.Base.Common.func.MESSAGEBOX_SHOW({
													title: App.Base.common.param.MESSAGEBOX_NORMAL_TIPS,
													msg: '服务器请求操作失败，请稍候重试',
													icon: Ext.MessageBox.ERROR
												});	
											},
											scope: this,
											params: 'SYS_OP_CMD=' + encodeURIComponent(App.Base.common.param.OP_CMD_LOGIN_OUT)
										});
									}
								},
								scope: this
							});	
                        },
                        iconCls: 'x-button-mainframe-exit'
                    },
                        '-'
                ]
        	});
                      
		   mainbottomtoolbar = new Ext.Toolbar();
        
            //iframe: memory leak.
            /*mainiframepanel = new Ext.Panel({
                id: 'mainiframepanel',
                
                title: '欢迎页',
                border: false,
                
                //autoScroll: true,
                
                html: '<iframe id="oamainiframe" name="oamainiframe" src="" width="100%" height="100%" frameborder="no" border="0"></iframe>'
            });*/
        
            //tabPanel
            maincentertabpanel = new Ext.TabPanel({
        		tabPosition: 'top',
        		activeTab: 0,
        		border: false,
        		enableTabScroll: true,
        		autoDestroy: true,
				autoScroll: true,
        		defaults: {
        			autoScroll: true
        		},
        		    
        		items: [{
					title: '欢迎页',
					border: false,
					iconCls: 'x-tabpanel-systemmanage-tabpage',
					layout: 'fit'
					//html: '<img src="logo.bmp" width="100%" height="100%" />'
					//autoLoad: 'logo.bmp'
				}],
				
				listeners: {
					tabchange: function(tabPanel, tab){
						tab.doLayout();
					},
					scope: this
				}
            });
        
            //tree
            mainwesttreerootnode = new Ext.tree.AsyncTreeNode({
                id: App.Base.common.param.SYSTEM_MAIN_TREEPANEL_ROOTNODE_ID + MODULE_ID,
                icon: App.Base.common.param.SYSTEM_MAIN_TREEPANEL_ROOTNODE_ICON_URL,
				expandIcon: App.Base.common.param.SYSTEM_MAIN_TREEPANEL_ROOTNODE_EXPANDICON_URL,
                text: App.Base.common.param.SYSTEM_MAIN_TREEPANEL_ROOTNODE_NORMAL_TITLE,
				qtip: App.Base.common.param.SYSTEM_MAIN_TREEPANEL_ROOTNODE_QTIP,
				singleClickExpand: true
            });
                        
            mainwesttreepanel = new Ext.tree.TreePanel({
                id: 'systemMainFrameWestMainTreePanel',
                autoScroll: true,
				bodyStyle:'padding:1px 1px 1px 0',
				tbar: new Ext.Toolbar({
					border: false,
					items: ['-', {
						text: '刷新',

						handler: function(){
							mainwesttreerootnode.reload();
						},
						tooltip: {title: '提示：', text: '当系统菜单目录树显示不正常时，可以帮助重新加载系统菜单目录树内容'},
						iconCls: 'x-menu-mainframe-refresh'
					}, '-']
				}),
				
                root: mainwesttreerootnode,
                loader: new Ext.tree.TreeLoader({
					dataUrl: App.Base.common.param.SYSTEM_TREEPANEL_ASYNC_TREELOADER_DATAURL,
					baseParams: {
						module: MODULE_ID,
						params: '1'
					}
				})
                
            });
        
            mainwesttreepanel.on("click", function(node){
				if (node == null)
				{
					return;
				}

                node.select();

                if (node.isLeaf())
                {                    
                    createTabPageByTreeLeafNode(maincentertabpanel, node);
                }
            }, this);

			mainwesttreepanel.on("beforeexpandnode", function(node){
				node.select();
				node.setIcon(node.attributes['expandIcon']);				
			});

			mainwesttreepanel.on("beforecollapsenode", function(node){
				node.select();
				node.setIcon(node.attributes['icon']);				
			});

			mainwesttreepanel.on("load", function(node){
				Ext.getBody().unmask();
			});

            mainwesttreecontextmenu = new Ext.menu.Menu({
                id: 'mainwesttreecontextmenu',
                items: [{
                    id: 'mainframeopennodetabpagemenu',
                    text: '打开TAB页面',
                    iconCls: 'x-menu-mainframe-expand'
                }, {
                    id: 'mainframeclosenodetabpagemenu',
                    text: '关闭TAB页面',
                    iconCls: 'x-menu-mainframe-collapse'
                }, '-', {
                    id: 'mainframeexpandnodemenu',
                    text: '展开目录节点',
                    iconCls: 'x-menu-mainframe-expand'
                }, {
                    id: 'mainframecollapsenodemenu',
                    text: '折叠目录节点',
                    iconCls: 'x-menu-mainframe-collapse'
                }, '-', {
                    id: 'mainframereloadnodemenu',
                    text: '重载目录节点',
                    iconCls: 'x-menu-mainframe-refresh'
                }]
            });
            
            mainwesttreecontextmenu.on('click', function(menu, menuitem, e){
                mainwesttreecontextmenu.hide();
               
                var menuitemid = menuitem.getId();
                
                var currentselectedtreenode = mainwesttreepanel.getSelectionModel().getSelectedNode();

                switch(menuitemid)
                {
                    case 'mainframeopennodetabpagemenu':
                        createTabPageByTreeLeafNode(maincentertabpanel, currentselectedtreenode);
                        break;
                    case 'mainframeclosenodetabpagemenu':
                        closeTabPageByTreeLeafNode(maincentertabpanel, currentselectedtreenode);
                        break;
					case 'mainframeexpandnodemenu':
                        currentselectedtreenode.expand();
                        break;
                    case 'mainframecollapsenodemenu':
                        currentselectedtreenode.collapse();
                        break;
                    case 'mainframereloadnodemenu':
                        currentselectedtreenode.reload();
                        break;
                    default:
                        break;
                }
            }, this);

            mainwesttreepanel.on("contextmenu", function(node, e){
                e.preventDefault();
				node.select();

                if (node.isLeaf())
                {
					Ext.getCmp('mainframeopennodetabpagemenu').enable();
					Ext.getCmp('mainframeclosenodetabpagemenu').enable();
					Ext.getCmp('mainframeexpandnodemenu').disable();
					Ext.getCmp('mainframecollapsenodemenu').disable();
                }
                else
                {
					Ext.getCmp('mainframeexpandnodemenu').enable();
					Ext.getCmp('mainframecollapsenodemenu').enable();
					Ext.getCmp('mainframeopennodetabpagemenu').disable();
					Ext.getCmp('mainframeclosenodetabpagemenu').disable();
                }

				mainwesttreecontextmenu.showAt(e.getXY());
            }, this);
 
            //expanding the first layer of treepanel.
            mainwesttreerootnode.expand();
            
            mainviewport = new Ext.Viewport({
                //renderTo: Ext.getBody(),
                id: 'mainviewport',
                layout: 'border',
                items: [{
						region : 'north',
						height : 14,
						border: false,
						frame: false,
						layout : 'fit',
						items : [
							new Ext.Panel({
								html : App.Base.common.param.SYSTEM_LOGO_IMAGE_URL
							})
						]
							
					
								/*new Ext.Panel({
									//title : '<font size=3>' + App.Base.common.param.SYSTEM_LOGO_TITLE + '</font>',
									//html : App.Base.common.param.SYSTEM_LOGO_IMAGE_URL,
									layout : 'fit',
									items :[
										maintoptoolbar
									]
								})*/
							
					},{
						region:'south',
						
						height : 32,
						border: false,
						
						layout : 'fit',
						items :[
							mainbottomtoolbar
						]
					},{
						region:'west',
						title: App.Base.common.param.SYSTEM_LOGO_TITLE,
						width : 280,
						minWidth: 240,
						border: true,
						split : true,
						collapsible : true,
						
						layout : 'fit',
						items : [
							mainwesttreepanel
						]
					},{
						region:'center',
						frame: false,
						border: true,
						tbar: maintoptoolbar,
						layout: 'fit',
						items: [
							maincentertabpanel   //mainiframepanel
						]
				}]
            });

			/* 下面是测试页面*/
			//new App.OA.SystemManage.SystemMenusManage({id: "01", handler: treePanelRefresh, scope: this}).getMainPanel()
			//new App.OA.SystemManage.SystemModulesManage().getMainPanel()
			//new App.OA.SystemManage.SystemPermsTypeManage().getMainPanel()
			//maincentertabpanel.getActiveTab().add(new App.OA.SystemManage.SystemPermsTypeManage().getMainPanel());
			//maincentertabpanel.getActiveTab().add(new App.OA.TradeManage.tradeDaysManage().getMainPanel());
			//maincentertabpanel.getActiveTab().add(new App.Base.SystemManage.SystemPermsManage().getMainPanel());
			//maincentertabpanel.getActiveTab().add(new App.Base.SystemManage.SystemRolesManage().getMainPanel());
			//maincentertabpanel.getActiveTab().add(new App.BaseInfoManage.GoodsManage().getMainPanel());
			//maincentertabpanel.getActiveTab().add(new App.FundManage.FundInManage().getMainPanel());
			//maincentertabpanel.getActiveTab().add(new App.BaseInfoManage.OperatorManage().getMainPanel());
			//maincentertabpanel.getActiveTab().add(new App.BaseInfoManage.OrganManage().getMainPanel());
			//maincentertabpanel.getActiveTab().add(new App.Base.SystemManage.SystemRolesPermsManage().getMainPanel());
			//maincentertabpanel.getActiveTab().add(new App.Base.SystemManage.SystemMenusManage({id: "02", handler: treePanelRefresh, scope: this}).getMainPanel());
			//maincentertabpanel.getActiveTab().add(new App.Base.SystemManage.SystemUserTypeManage().getMainPanel());
			//maincentertabpanel.getActiveTab().add(new App.Base.SystemManage.SystemUsersManage().getMainPanel());
			//maincentertabpanel.getActiveTab().add(new App.Base.SystemManage.SystemUsersRolesManage().getMainPanel());
			maincentertabpanel.doLayout();
			//

        }
    };
}();

Ext.onReady(App.Base.SystemMainFrame.SysMainFrame.init, App.Base.SystemMainFrame.SysMainFrame);